<template>
  <div class="supplier-list">
    <div class="page-header">
      <h1>供应商管理</h1>
      <el-button type="primary" @click="showAddDialog = true">
        <el-icon><Plus /></el-icon>
        新增供应商
      </el-button>
    </div>

    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="关键词">
          <el-input
            v-model="searchForm.keyword"
            placeholder="请输入供应商编码、名称或联系人"
            style="width: 280px"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="supplierCode" label="供应商编码" width="120" />
        <el-table-column prop="supplierName" label="供应商名称" width="200" />
        <el-table-column prop="contactPerson" label="联系人" width="100" />
        <el-table-column prop="contactPhone" label="联系电话" width="130" />
        <el-table-column prop="contactEmail" label="联系邮箱" width="180" />
        <el-table-column prop="creditRating" label="信用等级" width="100" />
        <el-table-column prop="statusDesc" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.statusDesc }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          :current-page="pagination.current"
          :page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="showAddDialog"
      :title="editingSupplier ? '编辑供应商' : '新增供应商'"
      width="600px"
    >
      <el-form
        ref="supplierFormRef"
        :model="supplierForm"
        :rules="supplierFormRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="供应商编码" prop="supplierCode">
              <el-input v-model="supplierForm.supplierCode" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商名称" prop="supplierName">
              <el-input v-model="supplierForm.supplierName" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactPerson">
              <el-input v-model="supplierForm.contactPerson" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="supplierForm.contactPhone" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系邮箱" prop="contactEmail">
              <el-input v-model="supplierForm.contactEmail" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="信用等级" prop="creditRating">
              <el-select v-model="supplierForm.creditRating" style="width: 100%">
                <el-option label="AAA" value="AAA" />
                <el-option label="AA" value="AA" />
                <el-option label="A" value="A" />
                <el-option label="BBB" value="BBB" />
                <el-option label="BB" value="BB" />
                <el-option label="B" value="B" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="地址" prop="address">
          <el-input v-model="supplierForm.address" />
        </el-form-item>
        <el-form-item label="营业执照号" prop="businessLicense">
          <el-input v-model="supplierForm.businessLicense" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="supplierForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="supplierForm.description"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
        
        <!-- 供应商Logo上传 -->
        <el-form-item label="供应商Logo" prop="logo">
          <FileUpload
            :multiple="false"
            accept=".jpg,.jpeg,.png,.gif"
            :max-size="5"
            :current-file="supplierForm.logoUrl ? {
              fileId: supplierForm.logoFileId,
              fileName: supplierForm.logoFileName || '未命名文件',
              fileSize: supplierForm.logoFileSize || 0,
              fileType: supplierForm.logoFileType || 'image',
              accessUrl: supplierForm.logoUrl,
              createTime: new Date().toISOString()
            } : null"
            upload-text="选择Logo"
            tip-text="支持jpg、png、gif格式，文件大小不超过5MB"
            list-type="picture"
            @upload-success="handleLogoUploadSuccess"
            @file-removed="handleLogoRemoved"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddDialog = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue'
import {createSupplier, deleteSupplier, getSupplierById, getSuppliers, updateSupplier} from '@/api/supplier'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Plus, Refresh, Search} from '@element-plus/icons-vue'
import FileUpload from '@/components/FileUpload.vue'

const loading = ref(false)
const showAddDialog = ref(false)
const editingSupplier = ref(null)
const supplierFormRef = ref()

const searchForm = reactive({
  keyword: ''
})

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

const tableData = ref([])

const supplierForm = reactive({
  supplierCode: '',
  supplierName: '',
  contactPerson: '',
  contactPhone: '',
  contactEmail: '',
  address: '',
  businessLicense: '',
  creditRating: '',
  status: 1,
  description: '',
  logoFileId: '',
  logoUrl: '',
  // 新增用于显示的文件信息
  logoFileName: '',
  logoFileSize: 0,
  logoFileType: ''
})

const supplierFormRules = {
  supplierCode: [
    { required: true, message: '请输入供应商编码', trigger: 'blur' }
  ],
  supplierName: [
    { required: true, message: '请输入供应商名称', trigger: 'blur' }
  ],
  contactEmail: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  contactPhone: [
    { pattern: /^1[3-9]\d{9}$|^0\d{2,3}-?\d{7,8}$/, message: '请输入正确的电话号码', trigger: 'blur' }
  ]
}

// 获取供应商列表
const fetchSuppliers = async () => {
  try {
    loading.value = true
    const params = {
      current: pagination.current,
      size: pagination.size,
      keyword: searchForm.keyword
    }
    
    const response = await getSuppliers(params)
    // 处理供应商列表数据
    tableData.value = response.records.map(supplier => ({
      ...supplier,
      logoFileId: supplier.logoFileId || '',
      logoUrl: supplier.logoUrl || ''
    }))
    pagination.total = response.total
  } catch (error) {
    console.error('获取供应商列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchSuppliers()
}

// 重置
const handleReset = () => {
  searchForm.keyword = ''
  pagination.current = 1
  fetchSuppliers()
}

// 编辑供应商
const handleEdit = async (row) => {
  try {
    loading.value = true
    // 获取供应商详情，包含完整的文件信息
    const supplierDetail = await getSupplierById(row.id)

    console.error('获取供应商详情失败:', supplierDetail)

    editingSupplier.value = supplierDetail

    // 使用安全的方式赋值，避免undefined错误
    Object.assign(supplierForm, {
      supplierCode: supplierDetail.supplierCode || row.supplierCode || '',
      supplierName: supplierDetail.supplierName || row.supplierName || '',
      contactPerson: supplierDetail.contactPerson || row.contactPerson || '',
      contactPhone: supplierDetail.contactPhone || row.contactPhone || '',
      contactEmail: supplierDetail.contactEmail || row.contactEmail || '',
      address: supplierDetail.address || row.address || '',
      businessLicense: supplierDetail.businessLicense || row.businessLicense || '',
      creditRating: supplierDetail.creditRating || row.creditRating || '',
      status: supplierDetail.status !== undefined ? supplierDetail.status : (row.status !== undefined ? row.status : 1),
      description: supplierDetail.description || row.description || '',

      logoFileId: (supplierDetail.logoFile && supplierDetail.logoFile.fileId) || supplierDetail.logoFileId || row.logoFileId || '',
      logoUrl: (supplierDetail.logoFile && supplierDetail.logoFile.accessUrl) || supplierDetail.logoUrl || row.logoUrl || '',
      logoFileName: (supplierDetail.logoFile && supplierDetail.logoFile.fileName) || '',
      logoFileSize: (supplierDetail.logoFile && supplierDetail.logoFile.fileSize) || 0,
      logoFileType: (supplierDetail.logoFile && supplierDetail.logoFile.fileType) || ''
    })
    showAddDialog.value = true
  } catch (error) {
    console.error('获取供应商详情失败:', error)
    ElMessage.error('获取供应商详情失败')
  } finally {
    loading.value = false
  }
}

// 删除供应商
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确定删除供应商 "${row.supplierName}" 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteSupplier(row.id)
    ElMessage.success('删除成功')
    fetchSuppliers()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除供应商失败:', error)
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    const valid = await supplierFormRef.value.validate()
    if (!valid) return

    if (editingSupplier.value) {
      console.log('更新供应商，表单数据:', JSON.stringify(supplierForm))
      await updateSupplier(editingSupplier.value.id, supplierForm)
      ElMessage.success('更新成功')
    } else {
      console.log('创建供应商，表单数据:', JSON.stringify(supplierForm))
      await createSupplier(supplierForm)
      ElMessage.success('创建成功')
    }
    
    showAddDialog.value = false
    fetchSuppliers()
    resetForm()
  } catch (error) {
    console.error('提交失败:', error)
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(supplierForm, {
    supplierCode: '',
    supplierName: '',
    contactPerson: '',
    contactPhone: '',
    contactEmail: '',
    address: '',
    businessLicense: '',
    creditRating: '',
    status: 1,
    description: '',
    logoFileId: '',
    logoUrl: ''
  })
  editingSupplier.value = null
  supplierFormRef.value?.resetFields()
}

// 处理Logo上传成功
const handleLogoUploadSuccess = (fileData) => {
  if (!fileData) {
    console.error('文件上传数据为空')
    return
  }
  
  try {
    const fileInfo = Array.isArray(fileData) ? fileData[0] : fileData
    
    if (!fileInfo || typeof fileInfo !== 'object') {
      console.error('无效的文件信息', fileInfo)
      return
    }
    
    // 检查必要的属性是否存在
    if (!fileInfo.fileId) {
      console.error('文件ID不存在', fileInfo)
      return
    }
    
  supplierForm.logoFileId = fileInfo.fileId || ''
  supplierForm.logoUrl = fileInfo.accessUrl || ''
  supplierForm.logoFileName = fileInfo.fileName || ''
  supplierForm.logoFileSize = fileInfo.fileSize || 0
  supplierForm.logoFileType = fileInfo.fileType || ''
    
    console.log('Logo上传成功', { fileId: fileInfo.fileId, logoUrl: fileInfo.accessUrl })
  } catch (error) {
    console.error('处理Logo上传结果时出错:', error)
  }
}

// 处理Logo删除
const handleLogoRemoved = () => {
  supplierForm.logoFileId = ''
  supplierForm.logoUrl = ''
  supplierForm.logoFileName = ''
  supplierForm.logoFileSize = 0
  supplierForm.logoFileType = ''
}

// 分页大小改变
const handleSizeChange = (val) => {
  pagination.size = val
  pagination.current = 1
  fetchSuppliers()
}

// 当前页改变
const handleCurrentChange = (val) => {
  pagination.current = val
  fetchSuppliers()
}

onMounted(() => {
  fetchSuppliers()
})
</script>

<style scoped>
.supplier-list {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  color: #303133;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  margin: 0;
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>